package com.aaa.interceptor;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.java.Log;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ：XiaoxXuan
 * @date ：Created in 2022.09.07 13:39
 * @description：拦截登录
 * @modified By：
 */
@Log
public class LoginInterceptor implements HandlerInterceptor {

    //除了登录和前端页面，其他的请求都要拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录认证过滤器开始拦截");
        //如果用户未登录，拦截，并让他滚，去登录页面
        String contextPath = request.getContextPath();
        HttpSession session = request.getSession();
        //排除不需要拦截的资源
        String uri = request.getRequestURI();
        if (uri.contains("login")||uri.contains("front")||uri.contains("static")) {
            return  true;
        } else {
            Object userObj = session.getAttribute("user");
            //如果用户已经登录，放行
            if (ObjectUtil.isNotEmpty(userObj)) {
                return  true;
            } else {
                System.out.println("这里是没有放行");
                System.out.println(contextPath+"/views/login.jsp");
                response.sendRedirect( contextPath+"/views/login.jsp");
                //request.getRequestDispatcher(contextPath+"/views/login.jsp");
                return false;
            }
        }

    }

}